import router from './router'
import store from './store'
import { asyncRoutes } from './router'
import Storage from '@/untils/storage'
import { getUserRoutes } from '@/api/user'
//progress
import Progress from 'nprogress'
import 'nprogress/nprogress.css'
//message
import { Message } from 'element-ui'

const whiteList = ['/login']

router.beforeEach(async (to, from, next) => {
  let hasToken = Storage.get('token')
  Progress.start()
  if (hasToken) {
    if (to.path === '/login') {
      Progress.done()
      next(false)
      return
    }
    if (!store.state.user.myRoutes) {
      let res = await getUserRoutes()
      let userRoutes = res.menuList
      let realRoutes = []
      asyncRoutes.map((val, ind) => {
        if (userRoutes[ind].name == val.name) {
          let tempRoute = { ...val }
          realRoutes.push(tempRoute)
          realRoutes[ind].children = []
          userRoutes[ind].children.map((cVal, cInd) => {
            if (cVal.name == val.children[cInd].name) {
              realRoutes[ind].children.push(val.children[cInd])
            }
          })
        }
      })
      realRoutes.push({ path: '*', redirect: '/404', hidden: true })
      realRoutes.map(item => {
        router.options.routes.push(item)
      })
      await router.addRoutes(realRoutes)
      store.dispatch('setRoutes', true)
      next(to)
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
  next()
  Progress.done()
})

router.afterEach(() => {
  Progress.done() // 结束Progress
})
